package cn.tedu.mall.book.controller;

import cn.tedu.mall.book.pojo.dto.UserAddNewDTO;
import cn.tedu.mall.book.pojo.dto.UserLoginDTO;
import cn.tedu.mall.book.pojo.dto.UserUpdateDTO;
import cn.tedu.mall.book.pojo.vo.UserStandardVO;
import cn.tedu.mall.book.service.impl.UserServiceImpl;
import cn.tedu.mall.book.web.JsonPage;
import cn.tedu.mall.book.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RequestMapping("/users")
@RestController
@Api(tags = "用户控制层管理")

public class UserController {
    @Autowired
    UserServiceImpl userService;

    @PostMapping("/reg")
    @ApiOperation("用户注册管理")
    public JsonResult<Void> reg(@Validated @RequestBody UserAddNewDTO userAddNewDTO){
        System.out.println("userAddNewDTO = " + userAddNewDTO);
        userService.insertUser(userAddNewDTO);
        return JsonResult.ok();
    }
    /* 登录功能 */
    @PostMapping("/login")
    public JsonResult<UserStandardVO> login(@Validated @RequestBody UserLoginDTO userLoginDTO, HttpSession session) {
        UserStandardVO userStandardVO = userService.loginUser(userLoginDTO, session);
        return JsonResult.ok(userStandardVO);
    }


    @PostMapping("/update")
    public JsonResult update(@RequestBody UserUpdateDTO userUpdateDTO){
        userService.updateById(userUpdateDTO);
        return JsonResult.ok();
    }


    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "page",example = "1"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",example = "10")
    })
    public JsonResult<JsonPage<UserStandardVO>> getList(Integer page,Integer pageSize){
        System.out.println("page = " + page + ", pageSize = " + pageSize);
        return JsonResult.ok(userService.getUserList(page,pageSize));
    }

    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public JsonResult logout(HttpSession session){
        //把登录成功时的数据删除
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
